# -*- coding: utf-8 -*-
import KBEngine
import IKernel
import MsgDef
import ErrorCodeDef
import ConstDef
import NameModDef
import time
import random
import LogDef
from KBEDebug import *


class NameModule:
	def __init__(self):
		pass

	def init(self, isReload):
		IKernel.Instance().registerFunc("NameModule.onCellMsg", self.onCellMsg)

		IKernel.Instance().addIntMsgCallback(MsgDef.CELL2BASE_NAME_MSG, "NameModule.onCellMsg")

	def end(self):
		pass

	def onCellMsg(self, senderEntityID, receiverEntityID, args):
		DEBUG_MSG("NameModule.onCellMsg receiverEntityID=%s" % str(receiverEntityID))
		dispatcher = {
			NameModDef.SUB_MSG_CHANGE_NAME : self.reqSaveName,
		}
		submsg = args[1]
		funcAddr = dispatcher.get(submsg)
		if funcAddr == None:
			return
		funcAddr(receiverEntityID, args)

	def reqSaveName(self, playerEntityID, args):
		newName = args[2]

		playerEntity = KBEngine.entities.get(playerEntityID)
		playerEntity.oldName = playerEntity.beforehandName
		playerEntity.beforehandName = newName
		playerEntity.writeToDB(self.saveNameResult)

	def saveNameResult(self, success, playerEntity):
		if success == False:
			playerEntity.beforehandName = playerEntity.oldName

		playerEntity.oldName = None

		msg = []
		msg.append(MsgDef.BASE2CELL_NAME_MSG)
		msg.append(NameModDef.SUB_MSG_CHANGE_NAME)
		msg.append(success)
		msg.append(playerEntity.beforehandName)
		IKernel.Instance().sendCellMsg(playerEntity.id, playerEntity.id, msg)
